<template>
  <view class="drone-login-container">
    <!-- 动态背景 -->
    <view class="animated-bg">
      <!-- 星空背景 -->
      <view class="stars" v-for="(star, index) in stars" :key="index" 
            :style="{
              left: `${star.left}%`,
              top: `${star.top}%`,
              width: `${star.size}px`,
              height: `${star.size}px`,
              opacity: star.opacity,
              animationDuration: `${star.duration}s`,
              animationDelay: `${star.delay}s`
            }">
      </view>
      
      <!-- 无人机编队 -->
      <view class="drone" v-for="(drone, index) in drones" :key="'d'+index"
            :style="{
              transform: `translate(${drone.x}px, ${drone.y}px) rotate(${drone.rotate}deg)`,
              filter: `drop-shadow(0 0 8px rgba(0, 198, 255, ${drone.glow}))`
            }">
        <image src="/static/drone-icon.png" mode="aspectFit"></image>
      </view>
      
      <!-- 雷达扫描效果 -->
      <view class="radar-scan" :style="{transform: `rotate(${scanAngle}deg)`}"></view>
    </view>
    
    <!-- 登录面板 -->
    <view class="login-panel" :class="{'panel-active': panelActive}">
      <view class="panel-header">
        <image src="/static/drone-logo.png" class="logo"></image>
        <view class="title">天穹<span class="highlight">无人机</span></view>
        <view class="subtitle">SKYLINE DRONE CONTROL SYSTEM</view>
      </view>
      
      <view class="panel-body">
        <view class="input-group">
          <view class="input-field" :class="{'active': activeField === 'phone'}">
            <u-icon name="phone" color="#00c6ff" size="22"></u-icon>
            <input 
              type="number" 
              v-model="loginForm.phone" 
              placeholder="请输入飞行号码" 
              placeholder-class="placeholder"
              @focus="activeField = 'phone'"
              @blur="activeField = ''"
            />
            <view class="country-code">+86</view>
          </view>
          
          <view class="input-field" :class="{'active': activeField === 'code'}">
            <u-icon name="lock" color="#00c6ff" size="22"></u-icon>
            <input 
              type="number" 
              v-model="loginForm.code" 
              placeholder="请输入飞行验证码" 
              placeholder-class="placeholder"
              @focus="activeField = 'code'"
              @blur="activeField = ''"
            />
            <view class="get-code" @click="getVerifyCode" :class="{'disabled': !canGetCode}">
              {{ codeText }}
            </view>
          </view>
        </view>
        
        <view class="action-group">
          <view class="login-btn" @click="handleLogin" :class="{'loading': loading}">
            <text>登录\注册</text>
            <view class="btn-glow"></view>
          </view>
          
          <view class="quick-login">
            <view class="divider">
              <view class="line"></view>
              <text>快速接入</text>
              <view class="line"></view>
            </view>
            
            <view class="social-login">
              <view class="social-icon" @click="wechatLogin">
                <u-icon name="weixin-fill" color="#09BB07" size="28"></u-icon>
              </view>
              <view class="social-icon" @click="fingerprintLogin">
                <u-icon name="fingerprint" color="#FF9800" size="28"></u-icon>
              </view>
            </view>
          </view>
        </view>
      </view>
      
     <!-- <view class="panel-footer">
        <text @click="navToRegister">注册飞行终端</text>
        <text>|</text>
        <text @click="navToReset">重置飞行密码</text>
      </view> -->
    </view>
    
    <!-- 状态指示灯 -->
    <view class="status-light" :class="{'connecting': loading}"></view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      loginForm: {
        phone: '',
        code: ''
      },
      activeField: '',
      loading: false,
      canGetCode: true,
      codeText: '获取飞行验证码',
      panelActive: false,
      
      // 背景动画数据
      stars: Array(50).fill().map(() => ({
        left: Math.random() * 100,
        top: Math.random() * 100,
        size: 1 + Math.random() * 3,
        opacity: 0.2 + Math.random() * 0.5,
        duration: 3 + Math.random() * 4,
        delay: Math.random() * 5
      })),
      
      drones: Array(3).fill().map((_, i) => ({
        x: Math.random() * 200 - 100,
        y: Math.random() * 100 - 50,
        rotate: Math.random() * 360,
        glow: 0.3,
        xSpeed: (Math.random() - 0.5) * 0.8,
        ySpeed: (Math.random() - 0.5) * 0.8,
        rotateSpeed: (Math.random() - 0.5) * 0.5
      })),
      
      scanAngle: 0
    }
  },
  mounted() {
    this.startAnimations();
    setTimeout(() => {
      this.panelActive = true;
    }, 300);
  },
  methods: {
    async getVerifyCode() {
      if (!this.canGetCode || this.isLocked) return
            
            // 校验手机号
            if (!this.validatePhone(this.loginForm.phone)) return
            
            // 检查发送频率限制（同一手机号60秒内只能发送一次）
            const lastSendTime = uni.getStorageSync(`lastSendTime_${this.loginForm.phone}`)
            if (lastSendTime && Date.now() - lastSendTime < 60000) {
              uni.showToast({
                title: '操作过于频繁，请稍后再试',
                icon: 'none'
              })
              return
            }
            
            this.canGetCode = false
            let seconds = 60
            
            // 显示发送中状态
            uni.showLoading({
              title: '发送飞行验证码中...',
              mask: true
            })
            
            try {
              // 模拟API请求
              const res = await this.$api.sendVerifyCode({
                phone: this.loginForm.phone,
                scene: 'login' // 区分场景
              })
              
              // 实际开发中替换为真实API调用
              // const res = await uni.request({
              //   url: '/api/auth/send-code',
              //   method: 'POST',
              //   data: {
              //     phone: this.loginForm.phone,
              //     scene: 'login'
              //   }
              // })
              
              uni.hideLoading()
              
              if (res.code === 200) {
                // 记录发送时间
                uni.setStorageSync(`lastSendTime_${this.loginForm.phone}`, Date.now())
                
                // 开始倒计时
                const timer = setInterval(() => {
                  seconds--
                  this.codeText = `${seconds}s后重新获取`
                  
                  if (seconds <= 0) {
                    clearInterval(timer)
                    this.codeText = '获取飞行验证码'
                    this.canGetCode = true
                  }
                }, 1000)
                
                uni.showToast({
                  title: '验证码已发送至飞行终端',
                  icon: 'none'
                })
              } else {
                this.canGetCode = true
                uni.showToast({
                  title: res.message || '验证码发送失败',
                  icon: 'none'
                })
              }
            } catch (error) {
              this.canGetCode = true
              uni.hideLoading()
              uni.showToast({
                title: '网络异常，请稍后重试',
                icon: 'none'
              })
              console.error('发送验证码失败:', error)
            }
    },
	// 验证手机号格式
	validatePhone(phone) {
	  const reg = /^1[3-9]\d{9}$/
	  if (!phone) {
		uni.showToast({
		  title: '请输入手机号码',
		  icon: 'none'
		})
		return false
	  }
	  if (!reg.test(phone)) {
		uni.showToast({
		  title: '手机号码格式不正确',
		  icon: 'none'
		})
		return false
	  }
	  return true
	},
	// 验证验证码格式
	validateCode(code) {
	  if (!code) {
		uni.showToast({
		  title: '请输入飞行验证码',
		  icon: 'none'
		})
		return false
	  }
	  if (!/^\d{6}$/.test(code)) {
		uni.showToast({
		  title: '验证码为6位数字',
		  icon: 'none'
		})
		return false
	  }
	  return true
	},
	 // 获取设备唯一标识
	getDeviceId() {
	  let deviceId = uni.getStorageSync('device_id')
	  if (!deviceId) {
		deviceId = 'd_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
		uni.setStorageSync('device_id', deviceId)
	  }
	  return deviceId
	},
    async handleLogin() {
      if (this.loading || this.isLocked) return
            
            // 基础校验
            if (!this.validatePhone(this.loginForm.phone)) return
            if (!this.validateCode(this.loginForm.code)) return
            
            // 检查是否在锁定状态
            if (this.isLocked) {
              const remainingTime = Math.ceil((this.lockTime - Date.now()) / 1000)
              uni.showToast({
                title: `终端已锁定，请${remainingTime}秒后再试`,
                icon: 'none'
              })
              return
            }
            
            this.loading = true
            
            try {
              // 模拟API请求
              // const res = await this.$api.login({
              //   phone: this.loginForm.phone,
              //   code: this.loginForm.code,
              //   deviceId: this.getDeviceId() // 获取设备唯一标识
              // })
              
              // 实际开发中替换为真实API调用
              // const res = await uni.request({
              //   url: '/api/auth/login',
              //   method: 'POST',
              //   data: {
              //     phone: this.loginForm.phone,
              //     code: this.loginForm.code,
              //     deviceId: this.getDeviceId()
              //   }
              // })
              uni.reLaunch({
              						url:'/pages/roleSelect/roleSelect'
              					})
              if (res.code === 200) {
                // 登录成功处理
                this.errorCount = 0
                
                // 存储token
                uni.setStorageSync('access_token', res.data.token)
                uni.setStorageSync('user_info', res.data.userInfo)
                
                uni.showToast({
                  title: '登录成功',
                  icon: 'success'
                })
                
                // 跳转到控制面板
                setTimeout(() => {
					uni.reLaunch({
						url:'/pages/roleSelect/roleSelect'
					})
                  // uni.switchTab({
                  //   url: '/pages/index/index'
                  // })
                }, 1500)
              } else {
                // 错误处理
                this.handleLoginError(res.code, res.message)
              }
            } catch (error) {
              console.error('登录失败:', error)
			  uni.showToast({
			    title: '登录成功',
			    icon: 'success'
			  })
			  setTimeout(() => {
				 
			    uni.switchTab({
			      url: '/pages/index/index'
			    })
			  }, 1500)
			
              // uni.showToast({
              //   title: '网络异常，请稍后重试',
              //   icon: 'none'
              // })
            } finally {
              this.loading = false
            }
    },
	// 处理登录错误
	handleLoginError(code, message) {
	  this.errorCount++
	  
	  // 错误次数超过限制
	  if (this.errorCount >= 5) {
		this.lockAccount()
		return
	  }
	  
	  // 根据错误码显示不同提示
	  let errorMsg = message || '登录失败'
	  switch(code) {
		case 4001:
		  errorMsg = '验证码已过期'
		  break
		case 4002:
		  errorMsg = '验证码错误'
		  break
		case 4003:
		  errorMsg = '终端未注册'
		  break
		case 4004:
		  errorMsg = '终端已被禁用'
		  break
	  }
	  
	  uni.showToast({
		title: errorMsg,
		icon: 'none'
	  })
	},
	// 锁定账号
	lockAccount() {
	  this.isLocked = true
	  this.lockTime = Date.now() + 5 * 60 * 1000 // 锁定5分钟
	  
	  // 显示锁定提示
	  uni.showToast({
		title: '尝试次数过多，终端已锁定5分钟',
		icon: 'none',
		duration: 3000
	  })
	  
	  // 启动解锁倒计时
	  const timer = setInterval(() => {
		const remainingTime = Math.ceil((this.lockTime - Date.now()) / 1000)
		
		if (remainingTime <= 0) {
		  clearInterval(timer)
		  this.isLocked = false
		  this.errorCount = 0
		}
	  }, 1000)
	},
    wechatLogin() {
      uni.showLoading({
        title: '正在接入微信飞行账号...',
        mask: true
      });
      
      setTimeout(() => {
        uni.hideLoading();
        uni.getUserProfile({
          desc: '用于验证飞行权限',
          success: () => {
            uni.showToast({
              title: '微信飞行账号接入成功',
              icon: 'success'
            });
            uni.switchTab({
              url: '/pages/control-panel'
            });
          },
          fail: () => {
            uni.showToast({
              title: '飞行权限验证失败',
              icon: 'none'
            });
          }
        });
      }, 1500);
    },
    fingerprintLogin() {
      uni.showLoading({
        title: '正在验证生物识别...',
        mask: true
      });
      
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: '生物识别验证成功',
          icon: 'success'
        });
        uni.switchTab({
          url: '/pages/control-panel'
        });
      }, 1500);
    },
    navToRegister() {
      uni.navigateTo({
        url: '/pages/register'
      });
    },
    navToReset() {
      uni.navigateTo({
        url: '/pages/reset-password'
      });
    },
    startAnimations() {
      // 无人机动画
      const animateDrones = () => {
        this.drones.forEach(drone => {
          drone.x += drone.xSpeed;
          drone.y += drone.ySpeed;
          drone.rotate += drone.rotateSpeed;
          drone.glow = 0.3 + Math.sin(Date.now() * 0.005) * 0.2;
          
          if (drone.x > 150 || drone.x < -150) drone.xSpeed *= -1;
          if (drone.y > 80 || drone.y < -80) drone.ySpeed *= -1;
        });
        requestAnimationFrame(animateDrones);
      };
      
      // 雷达扫描动画
      const scanAnimation = () => {
        this.scanAngle = (this.scanAngle + 0.5) % 360;
        requestAnimationFrame(scanAnimation);
      };
      
      animateDrones();
      scanAnimation();
    }
  }
}
</script>

<style lang="scss" scoped>
.drone-login-container {
  height: 100vh;
  background: linear-gradient(to bottom, #0a0e23, #1a1f3a);
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden;
  
  .animated-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    
    .stars {
      position: absolute;
      background-color: #fff;
      border-radius: 50%;
      animation: twinkle infinite alternate;
      
      @keyframes twinkle {
        0% { opacity: 0.2; transform: scale(1); }
        100% { opacity: 0.8; transform: scale(1.2); }
      }
    }
    
    .drone {
      position: absolute;
      top: 50%;
      left: 50%;
      width: 60px;
      height: 60px;
      transition: transform 0.8s ease-out;
      
      image {
        width: 100%;
        height: 100%;
      }
    }
    
    .radar-scan {
      position: absolute;
      bottom: 10%;
      left: 50%;
      width: 200%;
      height: 200%;
      background: linear-gradient(
        to right,
        transparent,
        transparent,
        rgba(0, 198, 255, 0.1),
        transparent,
        transparent
      );
      transform-origin: 25% 50%;
      pointer-events: none;
    }
  }
  
  .login-panel {
    width: 86%;
    max-width: 500px;
    padding: 40rpx;
    background: rgba(16, 22, 48, 0.8);
    border-radius: 16px;
    border: 1px solid rgba(0, 198, 255, 0.2);
    box-shadow: 0 0 30px rgba(0, 198, 255, 0.1);
    backdrop-filter: blur(10px);
    transform: translateY(40px);
    opacity: 0;
    transition: all 0.6s cubic-bezier(0.23, 1, 0.32, 1);
    z-index: 10;
    
    &.panel-active {
      transform: translateY(0);
      opacity: 1;
    }
    
    .panel-header {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 50rpx;
      
      .logo {
        width: 100rpx;
        height: 100rpx;
        margin-bottom: 20rpx;
      }
      
      .title {
        font-size: 38rpx;
        color: #fff;
        font-weight: 500;
        letter-spacing: 2rpx;
        margin-bottom: 10rpx;
        
        .highlight {
          color: #00c6ff;
          font-weight: bold;
        }
      }
      
      .subtitle {
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.6);
        letter-spacing: 1rpx;
      }
    }
    
    .panel-body {
      .input-group {
        margin-bottom: 50rpx;
        
        .input-field {
          height: 100rpx;
          display: flex;
          align-items: center;
          border-bottom: 1px solid rgba(0, 198, 255, 0.3);
          margin-bottom: 40rpx;
          position: relative;
          transition: all 0.3s ease;
          
          &.active {
            border-bottom-color: #00c6ff;
            
            .country-code {
              color: #00c6ff;
            }
          }
          
          input {
            flex: 1;
            height: 100%;
            color: #fff;
            font-size: 30rpx;
            padding-left: 20rpx;
          }
          
          .country-code {
            color: rgba(255, 255, 255, 0.7);
            font-size: 28rpx;
            margin-left: 10rpx;
            transition: all 0.3s ease;
          }
          
          .get-code {
            color: #00c6ff;
            font-size: 26rpx;
            padding: 8rpx 20rpx;
            border: 1px solid #00c6ff;
            border-radius: 30rpx;
            
            &.disabled {
              color: rgba(255, 255, 255, 0.3);
              border-color: rgba(255, 255, 255, 0.3);
            }
          }
        }
      }
      
      .action-group {
        .login-btn {
          height: 90rpx;
          background: linear-gradient(to right, #0072ff, #00c6ff);
          border-radius: 45rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          color: #fff;
          font-size: 32rpx;
          letter-spacing: 4rpx;
          position: relative;
          overflow: hidden;
          box-shadow: 0 0 20px rgba(0, 198, 255, 0.3);
          
          &.loading {
            text {
              opacity: 0;
            }
            
            &::after {
              content: "";
              position: absolute;
              width: 30rpx;
              height: 30rpx;
              border: 4rpx solid transparent;
              border-top-color: #fff;
              border-radius: 50%;
              animation: spin 0.8s linear infinite;
            }
          }
          
          .btn-glow {
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: linear-gradient(
              to bottom right,
              transparent,
              transparent,
              transparent,
              rgba(255, 255, 255, 0.3)
            );
            transform: rotate(30deg);
            animation: btnLight 3s linear infinite;
          }
        }
        
        .quick-login {
          margin-top: 50rpx;
          
          .divider {
            display: flex;
            align-items: center;
            margin-bottom: 40rpx;
            color: rgba(255, 255, 255, 0.5);
            font-size: 26rpx;
            
            .line {
              flex: 1;
              height: 1px;
              background-color: rgba(0, 198, 255, 0.3);
              margin: 0 20rpx;
            }
          }
          
          .social-login {
            display: flex;
            justify-content: center;
            gap: 60rpx;
            
            .social-icon {
              width: 80rpx;
              height: 80rpx;
              border-radius: 50%;
              background: rgba(255, 255, 255, 0.1);
              display: flex;
              justify-content: center;
              align-items: center;
              transition: all 0.3s ease;
              
              &:active {
                transform: scale(0.9);
                background: rgba(255, 255, 255, 0.2);
              }
            }
          }
        }
      }
    }
    
    .panel-footer {
      display: flex;
      justify-content: center;
      margin-top: 50rpx;
      color: rgba(255, 255, 255, 0.6);
      font-size: 26rpx;
      
      text {
        margin: 0 20rpx;
        
        &:active {
          color: #00c6ff;
        }
      }
    }
  }
  
  .status-light {
    position: absolute;
    bottom: 40rpx;
    right: 40rpx;
    width: 16rpx;
    height: 16rpx;
    border-radius: 50%;
    background-color: #ff3b30;
    box-shadow: 0 0 10px #ff3b30;
    transition: all 0.3s ease;
    
    &.connecting {
      background-color: #34c759;
      box-shadow: 0 0 10px #34c759;
      animation: pulse 1.5s infinite;
    }
  }
}

.placeholder {
  color: rgba(255, 255, 255, 0.3);
  font-size: 30rpx;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

@keyframes btnLight {
  to { transform: translateX(100%) translateY(100%) rotate(30deg); }
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}
</style>